package smfbackup.http;

import java.util.Enumeration;
import java.util.Hashtable;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.log4j.Logger;

/**
 * Basic implementation of a cookie jar.
 * <br/>
 * Can read the cookies given an array of Header objects and then put them back on 
 * a given Method (either Get or Post).
 * 
 * @author Iulian Virtejanu
 */
public class SMFCookieContainer {
    
    /**
     * Logger instance.
     */
    private Logger log = Logger.getLogger(SMFCookieContainer.class);
    
    /**
     * Internal cookie container.
     */
    Hashtable<String, String> cookies = new Hashtable<String, String>();
    
    /** Creates a new instance of CookieContainer */
    public SMFCookieContainer() {
    }
    
    /**
     * Saves each "Set-Cookie: ... " values in the cookie jar. They can be used later
     * by using the loadCookies(Method method) method.
     * 
     * @param headers - Headers object where the cookies should be searched for.
     */
    public void saveCookies(Header headers[]) {
        
        for (int i = 0; i < headers.length; i++) {
            if ("Set-Cookie".equals(headers[i].getName())) {
               String shortCookie[] = trimCookiePathAndDomain(headers[i].getValue()).split("=");
               cookies.put(shortCookie[0], shortCookie[1]);
               log.debug("Cookies saved so far: " + cookies);
            }
        }
    }
    
    /**
     * Adds a "Cookie: ... " header to the request method based on the cookies
     * that were previously saved by saveCookies(Header headers[]);
     * <br/>
     * Cookies are combined using "; " as separator.
     * <br/>
     * In case of cookies having the same name, only last one in the header is kept.
     * @param method - Method (Get/Post) where the Cookie header should be added.
     */
    public void loadCookies(HttpMethod method) {
        String cookie = "";
        Enumeration<String> names = cookies.keys();
        while (names.hasMoreElements())
        {
            String cookieName = names.nextElement();
            cookie += cookieName + "=" + cookies.get(cookieName);
            if (names.hasMoreElements())
                cookie += "; ";
        }

        log.debug("Setting Cookie header to: " + cookie);
        method.setRequestHeader("Cookie", cookie);
    }
    
    /**
     * Resets the cookies container.
     */
    public void resetCookies()
    {
        cookies = new Hashtable<String, String>();
    }
    
    /**
     * Trims the cookie's path and domain. As we know what domain it is and what path.
     * <br/>
     * <code>Set-Cookie: PHPSESSID=5e4ca56513f02907309ea3e5dc13ef79; path=/; domain=.example.com</code>
     * @param fullCookie
     * @return Returns only the first part, cookieName=cookieValue
     */
    private String trimCookiePathAndDomain(String fullCookie)
    {
        log.debug("Full cookie: " + fullCookie);
        if (fullCookie.indexOf(';') >= 0)
            return fullCookie.substring(0, fullCookie.indexOf(';'));
        else
            return fullCookie;
    }
}
